import dayjs from "dayjs";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList, deviceDetection } from "@pureadmin/utils";
import {getDeptList, getShopGroupList} from "@/api/system";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { useRouter,useRoute } from 'vue-router';
import {hasPerms} from "@/utils/auth";

export function usePurchaseUser(treeRef: Ref) {
  const route = useRoute();
  const form = reactive({
    name: "",
    code: "",group: route.query?.group||"",
    status: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const depsAll = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {label: "Id", prop: "id",width: 120},
    {label: "网站分组名称", prop: "group_name"},
    {label: "状态", cellRenderer: scope => (
        <el-switch
          size={scope.props.status === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2} disabled={!hasPerms('shopGroup:btn:edit')}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      width: 90
    },
    //const result = data
    //   .filter(item => [12, 14].includes(item.id))
    //   .map(item => item.department_name);
    {label: "业务员组", prop: "dep_ids",minWidth:160,
      cellRenderer: scope => (depsAll.value.filter(x=>scope.row.dep_ids.includes(x.id)).map(x=>x.department_name).join(";")),},
    {label: "创建时间", prop: "created_at",width:140},
    {label: "添加人员", prop: "creator",width:140},
    {label: "备注", prop: "remark"},
    {label: "操作", fixed: "right", width: 210, slot: "operation"}
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${ row.category_name}</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    ).then(() => {
      row.swith = 1
      getShopGroupList(row,"put").then(res=>{
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
        message(`已${row.status === 2 ? "停用" : "启用"}${row.group_name}店铺分组`, {
          type: "success"
        });
      })
    }).catch(() => {
        row.status === 2 ? (row.status = 1) : (row.status = 2);
      });
  }

  function handleDelete(row) {
    getShopGroupList(row,"delete").then(res=>chores(row,res,'删除',onSearch))
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    const { data } = await getShopGroupList(toRaw(form),'get');
    dataList.value = data.data;
    depsAll.value = data.dep_list;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function chores(curData,res,title,done) {
    if(res.code===0){
      message(`您${title}了店铺分组为${curData.group_name}的这条数据`, {
        type: "success"
      });
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    }else{
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }
  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}店铺分组`,
      props: {
        formInline: JSON.parse(JSON.stringify(row||{status:1})),
        depsAll:depsAll.value
      },
      width: "35%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              getShopGroupList(curData,"post").then(res=>chores(curData,res,title,done))
            } else {
              curData.id = row.id
              // 实际开发先调用修改接口，再进行下面操作
              getShopGroupList(curData,"put").then(res=>chores(curData,res,title,done))
            }
          }
        });
      }
    });
  }



  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  const onQueryChanged = (query: string) => {
      treeRef.value!.filter(query);
    };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };


  const router = useRouter(); // ✅ 正确获取路由实例
  const openNewTab = (path) => {
    let query = path.split('?')[1];
    if (!query){
      query = {};
    }else{
      query =  query.split('&').reduce((acc, pair) => {
        const [key, value] = pair.split('=');
        acc[key] = value;
        return acc;
      }, {});
    }
    router.push({
      path: path,
      query: query
    })
  }
  onMounted(async () => {
    onSearch();
  });


  return {
    form, isShow, curRow, loading, columns, rowStyle, dataList,
    isLinkage, pagination, isExpandAll, isSelectAll, depsAll, onSearch, resetForm, openDialog,
    handleDelete, filterMethod, transformI18n, onQueryChanged,openNewTab,
    handleSizeChange, handleCurrentChange, handleSelectionChange
  };
}
